package controllers

import (
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/beego/beego/v2/core/validation"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go/v4"

	"laojiequ.cn/models"
	"laojiequ.cn/utils"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Form() {
	c.TplName = "login.html"
}

func (c *UserController) Login() {
	//c.Ctx.Request.Header.
	username := c.GetString("username")
	password := c.GetString("password")
	mobile := c.GetString("mobile")
	sms := c.GetString("sms")
	valid := validation.Validation{}
	if mobile != "" {
		valid.Required(mobile, "mobile").Message("手机号不可以为空")
		valid.Required(sms, "sms").Message("验证码不可以为空")
		valid.Mobile(mobile, "mobile").Message("手机号格式有误")
		if valid.HasErrors() {
			for _, v := range valid.Errors {
				c.Data["json"] = map[string]interface{}{
					"message": v.Message,
					"model":   http.StatusAccepted,
				}
				c.ServeJSON()
				return
			}
		}
		key := "sms:" + mobile
		code := utils.GetRedisCode(key)
		smsInt, _ := strconv.Atoi(sms)
		if code != smsInt {
			c.Data["json"] = map[string]interface{}{
				"message": "验证码有误，请认真填写！！！",
				"model":   http.StatusAccepted,
			}
			c.ServeJSON()
			return
		}
		u, err := models.UserLoginByMobile(mobile)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"message": err.Error(),
				"model":   http.StatusAccepted,
			}
			c.ServeJSON()
			return
		}
		//生成token
		token := utils.CreateToken(&utils.MyCustomClaims{
			UserId: int64(u.Time.ID),
			StandardClaims: jwt.StandardClaims{
				ExpiresAt: jwt.NewTime(float64(time.Now().Unix() + 86400)),
			},
		})

		c.Data["json"] = map[string]interface{}{
			"message": "登录成功",
			"code":    http.StatusOK,
			"data": map[string]interface{}{
				"token": token,
				"user":  u,
			},
		}
		c.ServeJSON()
	}
	valid.Required(username, "username").Message("用户名不可以为空")
	valid.Required(password, "password").Message("密码不可以为空")
	if valid.HasErrors() {
		for _, v := range valid.Errors {
			c.Data["json"] = map[string]interface{}{
				"message": v.Message,
				"model":   http.StatusAccepted,
			}
			c.ServeJSON()
			return
		}
	}
	u, err := models.UserLoginByUsername(username, password)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"message": err.Error(),
			"code":    http.StatusAccepted,
		}
		c.ServeJSON()
		return
	}
	//设置 session
	c.SetSession("username", u.Time.ID)
	//将用户信息 储存到redis 缓冲中
	key := "user:" + username
	err = utils.RedisSet(key, u)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"message": err.Error(),
			"code":    http.StatusAccepted,
		}
		c.ServeJSON()
		return
	}
	fmt.Println(u)
	//生成token
	token := utils.CreateToken(&utils.MyCustomClaims{
		UserId: int64(u.Time.ID),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: jwt.NewTime(float64(time.Now().Unix() + 86400)),
		},
	})

	c.Data["json"] = map[string]interface{}{
		"message": "登录成功",
		"code":    http.StatusOK,
		"data": map[string]interface{}{
			"token": token,
			"user":  u,
		},
	}
	c.ServeJSON()
}

func (c *UserController) SendSms() {
	mobile := c.GetString("mobile")
	fmt.Println(mobile)
	valid := validation.Validation{}
	timesKey := "sms:" + "times"
	timeKey := "sms:" + "time"
	key := "sms:" + mobile
	valid.Required(mobile, "mobile").Message("手机号不可以为空")
	valid.Mobile(mobile, "mobile").Message("手机号格式有误")
	if valid.HasErrors() {
		for _, v := range valid.Errors {
			c.Data["json"] = map[string]interface{}{
				"message": v.Message,
				"model":   http.StatusAccepted,
			}
			c.ServeJSON()
			return
		}
	}
	if !utils.RedisExist(timeKey) {
		c.Data["json"] = map[string]interface{}{
			"message": "请勿频繁发送！！！",
			"model":   http.StatusAccepted,
		}
		c.ServeJSON()
		return
	}
	//生成 验证码
	code := utils.CreateCode()
	//存入redis

	err := utils.RedisSet(key, code)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"message": err.Error(),
			"model":   http.StatusAccepted,
		}
		c.ServeJSON()
		return
	}
	utils.RedisIncr(timesKey)
	utils.RedisTime(key, strconv.Itoa(code))
	if !utils.IhuY(mobile, code) {
		c.Data["json"] = map[string]interface{}{
			"message": "调用第三方库失败",
			"model":   http.StatusAccepted,
		}
		c.ServeJSON()
	}
	c.Data["json"] = map[string]interface{}{
		"message": "验证码发送成功",
		"model":   http.StatusOK,
		"data":    code,
	}
	c.ServeJSON()
}

func (c *UserController) RegisterForm() {
	c.TplName = "register.html"
}

func (c *UserController) Register() {
	mobile := c.GetString("mobile")
	sms := c.GetString("sms")
	valid := validation.Validation{}
	valid.Required(mobile, "mobile").Message("手机号不可以为空")
	valid.Mobile(mobile, "mobile").Message("手机号格式有误")
	if valid.HasErrors() {
		for _, v := range valid.Errors {
			c.Data["json"] = map[string]interface{}{
				"message": v.Message,
				"model":   http.StatusAccepted,
			}
			c.ServeJSON()
			return
		}
	}

	smsInt, _ := strconv.Atoi(sms)
	key := "sms:" + mobile
	code := utils.GetRedisCode(key)
	if smsInt != code {
		c.Data["json"] = map[string]interface{}{
			"message": "验证码有误，请认真填写！！！",
			"model":   http.StatusAccepted,
		}
		c.ServeJSON()
		return
	}
	err := models.UserInsert(mobile, &models.User{
		Username: sms,
		Password: "",
		Mobile:   mobile,
		Email:    "",
	})
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"message": err.Error(),
			"model":   http.StatusAccepted,
		}
		c.ServeJSON()
		return
	}
	//获取用户数据
	u, _ := models.UserLoginByMobile(mobile)

	token := utils.CreateToken(&utils.MyCustomClaims{
		UserId: int64(u.Time.ID),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: jwt.NewTime(float64(time.Now().Unix() + 86400)),
		},
	})
	c.Data["json"] = map[string]interface{}{
		"message": "注册成功",
		"code":    http.StatusOK,
		"data": map[string]interface{}{
			"token": token,
			"user":  u,
		},
	}
	c.ServeJSON()
	return

}

func (c *UserController) UpdatePaw() {
	c.TplName = "update.html"
}
